<template xmlns:v-bind="http://www.w3.org/1999/xhtml" xmlns:v-on="http://www.w3.org/1999/xhtml">
  <el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" label-width="120px" class="demo-ruleForm" id="block-space">
    <el-form-item label="用户名" prop="name" >
      <el-input  v-model="ruleForm.name" ></el-input>
    </el-form-item>
    <el-form-item prop="email" label="邮箱" >
      <el-input v-model="ruleForm.email"></el-input>
    </el-form-item>
    <el-form-item label="密码" prop="pass">
      <el-input type="password" v-model="ruleForm.pass" autocomplete="off"></el-input>
    </el-form-item>
    <el-form-item label="确认密码" prop="checkPass">
      <el-input type="password" v-model="ruleForm.checkPass" autocomplete="off"></el-input>
    </el-form-item>
    <el-form-item prop="code" label="验证码">
      <el-row :gutter="2">
        <el-col :span="10">
          <el-input type="text" auto-complete="off" v-model="ruleForm.code" placeholder="验证码" value="">
          </el-input>
        </el-col>
        <el-col :span="10">
          <el-button @click="sendMsg()" type="primary" :disabled="canClick" style="width: 125px; flex-direction: column" size="medium">{{ content }}</el-button>
        </el-col>
      </el-row>
    </el-form-item>

    <el-form-item style="margin-left: 10px;">
      <!--        <el-button @click="rt()">返回登录</el-button>-->

      <el-button type="primary" @click="submitForm('ruleForm')" >立即注册</el-button>

      <el-button @click="resetForm('ruleForm')" style="margin-left: 35px;">重置注册</el-button>
    </el-form-item>
  </el-form>

</template>

<script>
    export default {

      data() {
        var checkName = (rule, value, callback) => {
          if (value === '') {
            return callback(new Error('用户名不能为空'));
          }
          else {
            callback();
          }
        };
        var validatePass = (rule, value, callback) => {
          if (value === '') {
            callback(new Error('请输入密码'));
          } else {
            if (this.ruleForm.checkPass !== '') {
              this.$refs.ruleForm.validateField('checkPass');
            }
            callback();
          }
        };
        var validatePass2 = (rule, value, callback) => {
          if (value === '') {
            callback(new Error('请再次输入密码'));
          } else if (value !== this.ruleForm.pass) {
            callback(new Error('两次输入密码不一致!'));
          } else {
            callback();
          }
        };
        var checkEmail= (rule, value, callback) => {
          if (value === '') {
            return callback(new Error('邮箱不能为空'));
          }
          else {
            callback();
          }
        };
        return {
          content: '发送验证码',
          totalTime: 60,
          canClick: false,
          ruleForm: {
            pass: '',
            checkPass: '',
            name: '',
            email:'',
            code:'',
            codetrue:null,
          },
          rules: {
            pass: [
              { validator: validatePass, trigger: 'blur', required: true, }
            ],
            checkPass: [
              { validator: validatePass2, trigger: 'blur', required: true, }
            ],
            name: [
              { validator: checkName, trigger: 'blur' , required: true}
            ],
            email:[
              { validator: checkEmail, trigger: 'blur', required: true },
              {  message: '请输入邮箱地址' },
              { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
            ],
            code:[
              {required: true}
            ]
          }
        };
      },
      methods:{
        submitForm(formName) {

          this.$refs[formName].validate(async (valid) => {
            if (valid) {
              console.log(this.ruleForm.codetrue,this.ruleForm.code)
              if(this.ruleForm.codetrue===this.ruleForm.code) {
                var data = {'username': this.ruleForm.name, 'password': this.ruleForm.pass, 'email': this.ruleForm.email};
                var url = '/user/Register';
                this.$axios.post(url,data)
                  .then( (res)=> {
                      //document.write("data is coming", res.data.code);
                      if (res.data.code === 200) {
                        this.$message({message: res.data.msg, type: 'success'});
                        const sleep = (time) => {
                          return new Promise((resolve) => {
                            setTimeout(resolve, time);
                          });
                        };
                        sleep(2000).then(() => {
                          console.log(1);
                        });
                         location.reload(true);
                      }
                      else {
                        this.$message({message: res.data.msg, type: 'error'})
                      }
                    }).catch(function (error) {
                  console.log(error);
                    } );
              }
              else {
                this.$message({message: "验证码错误，请重新输入验证码！", type: 'error'});
              }
            }
          }
          );
          },

        resetForm(formName){
          this.$refs[formName].resetFields();
        },
        sendMsg() {
          if (this.ruleForm.email == '') {
            this.$message.error('邮箱未填写，请填写邮箱再点击发送！');
            return;
          } else {
            if (this.canClick) return;
            this.canClick = true;
            this.content = this.totalTime + 's后重新发送';
            let clock = window.setInterval(() => {
              this.totalTime--;
              this.content = this.totalTime + 's后重新发送';
              if (this.totalTime < 0) {
                window.clearInterval(clock);
                this.content = '发送验证码';
                this.totalTime = 60;
                this.canClick = false;
              }
            }, 1000);
            var str =this.ruleForm.email;
            var nstr = str.split('@');
            var url = '/sendEmail/'+nstr[nstr.length - 2]+'%40'+nstr[nstr.length - 1];
            this.$axios.get(url)
              .then( (res)=> {
                console.log(res.data.code);
                if (res.data.code == 200) {
                  this.$message({
                    message: res.data.msg,
                    type: 'success'
                  });
                  this.ruleForm.codetrue=res.data.data;
                  console.log(this.ruleForm.codetrue);
                } else {
                  this.$message({
                    message: res.data.msg,
                    type: 'error'
                  })
                }
              }).catch(function (error) {
              console.log(error);
            });
          }
        }

      }

    }
</script>

<style scoped>
  #block-space{
    border-spacing: 4px;
  }
</style>
